package cn.tedu.store.controller;

import cn.tedu.store.controller.ex.*;
import cn.tedu.store.service.ex.*;
import cn.tedu.store.util.JsonResult;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 统一处理业务层抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public JsonResult<Void> handleCustomException(Throwable e){
        JsonResult<Void> jr=new JsonResult<>();
        // 添加异常提示信息
        jr.setMsg(e.getMessage());
        // 添加异常状态
        if(e instanceof EmptyArgumentException){
            jr.setState(2001);
        }else if(e instanceof UserExistException){
            jr.setState(2002);
        }else if(e instanceof LoginException){
            jr.setState(2003);
        }else if(e instanceof ChangePasswordException){
            jr.setState(2004);
        }else if(e instanceof ChangeUserInfoException){
            jr.setState(2005);
        }else if(e instanceof AddressCountLimitException){
            jr.setState(2006);
        }else if(e instanceof RecordNotFoundException){
            jr.setState(2007);
        }else if(e instanceof InsertException){
            jr.setState(3000);
        }else if(e instanceof QueryException){
            jr.setState(4000);
        }else if(e instanceof UpdateException){
            jr.setState(5000);
        }else if(e instanceof UpdateException){
            jr.setState(7000);
        }else{
            jr.setState(2000);
        }

        return jr;
    }

    /**
     * 统一处理控制器层文件上传时抛出的异常
     * @param e
     * @return
     */
    @ExceptionHandler(FileUploadException.class)
    @ResponseBody
    public JsonResult<Void> handleFileUploadException(Throwable e){
        JsonResult<Void> jr=new JsonResult<>();
        // 添加异常提示信息
        jr.setMsg(e.getMessage());
        // 添加异常状态
        if(e instanceof FileEmptyException){
            jr.setState(6001);
        }else if(e instanceof FileIOException){
            jr.setState(6002);
        }else if(e instanceof FileSizeException){
            jr.setState(6003);
        }else if(e instanceof FileStateException){
            jr.setState(6004);
        }else if(e instanceof FileTypeException){
            jr.setState(6005);
        }else{
            jr.setState(6000);
        }
        return jr;
    }

}
